"""真实传感器数据处理器"""
import json
import os
from datetime import datetime
from .config import MEDIA_CONFIG, setup_logging

class DataProcessor:
    """统一的数据处理器"""
    
    def __init__(self):
        self.logger = setup_logging('Data')
        self.data_cache = {
            'location': None,
            'camera': None,
            'audio': None,
            'video': None
        }
    
    def generate_location_data(self):
        """获取真实位置数据"""
        try:
            # 尝试从GPS模块获取位置数据
            location_data = self._get_gps_data()
            if not location_data:
                raise Exception("GPS模块未连接")
            
            data = {
                "type": "location",
                "role": "hardware",
                "timestamp": self._get_timestamp(),
                "coordinates": {
                    "latitude": location_data['latitude'],
                    "longitude": location_data['longitude'],
                    "accuracy": location_data.get('accuracy', 0.0)
                },
                "address": location_data.get('address', '未知位置'),
                "speed": location_data.get('speed', 0),
                "direction": location_data.get('direction', 0)
            }
            
            self.data_cache['location'] = data
            self._save_json_data(data, '4G位置数据.json')
            return data
            
        except Exception as e:
            raise Exception(f"GPS模块未连接")
    
    def generate_camera_data(self, media_processor=None):
        """获取真实摄像头数据"""
        try:
            if not media_processor:
                raise Exception("摄像头未初始化")
            
            # 从真实摄像头捕获图像
            ret, frame = media_processor.capture_image()
            if not ret or frame is None:
                raise Exception("摄像头无法捕获图像")
            
            # 保存真实图像
            timestamp_str = datetime.now().strftime("%Y%m%d%H%M%S")
            filename = f"camera_image_{timestamp_str}.jpg"
            filepath = media_processor.save_image(frame, "camera_image")
            
            if not filepath:
                raise Exception("无法保存摄像头图像")
            
            # 获取真实图像信息
            file_size = os.path.getsize(filepath) if os.path.exists(filepath) else 0
            height, width = frame.shape[:2]
            
            # 获取摄像头类型信息
            camera_type = getattr(media_processor, 'camera_type', 'unknown')
            device_info = f"树莓派摄像头({camera_type})" if camera_type == 'picamera2' else f"USB摄像头({camera_type})"
            
            data = {
                "type": "camera_image",
                "role": "hardware",
                "timestamp": self._get_timestamp(),
                "image_data": {
                    "path": filepath,
                    "format": "jpg",
                    "resolution": f"{width}x{height}",
                    "size": file_size
                },
                "metadata": {
                    "device_id": self._get_camera_device_id(),
                    "device_type": device_info,
                    "camera_interface": camera_type,
                    "exposure": "auto",
                    "white_balance": "auto"
                }
            }
            
            self.data_cache['camera'] = data
            self._save_json_data(data, '摄像头图像数据.json')
            return data
            
        except Exception as e:
            raise Exception(f"摄像头无法捕获图像")
    
    def process_audio_data(self, audio_file_path):
        """处理音频数据"""
        data = self._load_json_file(audio_file_path)
        if data and data.get('type') == 'audio':
            self.data_cache['audio'] = data
            self.logger.info("音频数据已处理")
            return True
        return False
    
    def process_video_data(self, video_file_path):
        """处理视频数据"""
        data = self._load_json_file(video_file_path)
        if data and data.get('type') == 'video':
            self.data_cache['video'] = data
            self.logger.info("视频数据已处理")
            return True
        return False
    
    def get_all_data(self):
        """获取所有数据"""
        return self.data_cache.copy()
    
    def clear_cache(self):
        """清空缓存"""
        self.data_cache = {
            'location': None,
            'camera': None,
            'audio': None,
            'video': None
        }
        self.logger.info("数据缓存已清空")
    
    def _get_timestamp(self):
        """获取时间戳"""
        return datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
    
    def _load_json_file(self, filepath):
        """加载JSON文件"""
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            self.logger.error(f"文件未找到: {filepath}")
        except json.JSONDecodeError:
            self.logger.error(f"JSON格式错误: {filepath}")
        except Exception as e:
            self.logger.error(f"加载文件失败: {e}")
        return None
    
    def _save_json_data(self, data, filename):
        """保存JSON数据"""
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
        except Exception as e:
            self.logger.error(f"保存数据失败: {e}")
    
    def _get_gps_data(self):
        """从GPS模块获取位置数据"""
        try:
            # 这里应该实现真实的GPS数据获取逻辑
            # 例如从串口读取NMEA数据或使用GPS库
            # 目前抛出异常表示未实现真实GPS获取
            raise Exception("GPS模块未连接或未配置")
            
            # 示例代码（需要根据实际GPS模块实现）:
            # import serial
            # import pynmea2
            # 
            # ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
            # line = ser.readline().decode('ascii', errors='replace')
            # if line.startswith('$GPGGA'):
            #     msg = pynmea2.parse(line)
            #     return {
            #         'latitude': float(msg.latitude),
            #         'longitude': float(msg.longitude),
            #         'accuracy': float(msg.horizontal_dil) if msg.horizontal_dil else 0.0,
            #         'address': '未知位置',
            #         'speed': 0,
            #         'direction': 0
            #     }
            # return None
            
        except Exception as e:
            self.logger.error(f"GPS数据获取失败: {e}")
            return None
    
    def _get_camera_device_id(self):
        """获取摄像头设备ID"""
        try:
            # 这里应该实现获取真实摄像头设备ID的逻辑
            # 例如从系统信息或设备配置中获取
            import platform
            hostname = platform.node()
            return f"CAM_{hostname}_001"
        except Exception as e:
            self.logger.error(f"获取摄像头设备ID失败: {e}")
            return "CAM_UNKNOWN_001"